package cn.ghx.xboot.client;

import cn.ghx.xboot.douyin.dto.Code2SessionResult;
import com.baomidou.mybatisplus.extension.conditions.query.LambdaQueryChainWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import cn.ghx.xboot.mapper.ClientMapper;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

/**
 * @author ghx
 * @description 针对表【t_client(客户-抖音)】的数据库操作Service实现
 * @createDate 2024-03-08 10:47:07
 */
@Service
public class ClientService extends ServiceImpl<ClientMapper, Client> {

    public Client saveOrUpdateBySession(Code2SessionResult res) {
        Client origin = null;
        String sessionKey = res.getSessionKey();
        String openid = res.getOpenid();
        String anonymousOpenid = res.getAnonymousOpenid();
        String unionid = res.getUnionid();
        if (StringUtils.hasText(openid)) {
            origin = findByOpenid(openid);
        }
        if (origin == null) {
            if (StringUtils.hasText(anonymousOpenid)) {
                origin = findByAnonymousOpenid(anonymousOpenid);
            }
        }
        if (origin == null) {

            if (StringUtils.hasText(unionid)) {
                origin = findByUnionid(unionid);
            }
        }

        if (origin == null) {
            origin = new Client();
            origin.setOpenid(openid);
            origin.setAnonymousOpenid(anonymousOpenid);
            origin.setUnionid(unionid);
        }
        origin.setSessionKey(sessionKey);

        saveOrUpdate(origin);

        return origin;
    }

    private Client findByUnionid(String unionid) {
        return lambdaQuery().eq(Client::getUnionid, unionid).one();
    }

    private Client findByAnonymousOpenid(String anonymousOpenid) {
        return lambdaQuery().eq(Client::getAnonymousOpenid, anonymousOpenid).one();
    }

    private Client findByOpenid(String openid) {
        return lambdaQuery().eq(Client::getOpenid, openid).one();
    }

    public Page<Client> query(String keyword, Integer page, Integer size) {
        LambdaQueryChainWrapper<Client> qw = lambdaQuery();
        // 参数
        if (StringUtils.hasText(keyword)) {
            qw.and(w -> {
                w.like(Client::getName, keyword).or()
                        .like(Client::getNickName, keyword).or()
                        .like(Client::getPhoneNumber, keyword);
            });
        }
        return qw.page(Page.of(page, size));
    }

    public Client getByOpenId(String openid) {
        return lambdaQuery().eq(Client::getOpenid, openid).one();
    }
}




